<script setup lang='ts' name="sales-order-view">
import type { FormInstance } from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'

import { useJcOrderMetaGetOne, useReceiveOrder } from '@fl/api/supplier'
import { SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import NP from 'number-precision'
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const { params } = useRoute()

const router = useRouter()

const id = computed(() => {
    return params.id
})

const rules = {
    estimatedShippingDate: [
        { message: '请选择预计发货时间', required: true, trigger: 'blur' },
    ],
    supplierContactName: [
        { message: '请输入供应商联络人', required: true, trigger: 'blur' },
    ],
    supplierContactPhone: [
        { message: '请输入联络人手机号', required: true, trigger: 'blur' },
        {
            message: '手机号码格式不正确',
            pattern: /^1[3-9]\d{9}$/,
            trigger: 'blur',
        },
    ],
}

const { data, isLoading } = useJcOrderMetaGetOne(id)
const { isPending, mutate } = useReceiveOrder()
const tableRef = ref<VxeTableInstance<any>>()
const formRef = ref<any>()

const form = ref({
    estimatedShippingDate: '',
    remark: '',
    supplierContactName: '',
    supplierContactPhone: '',
})

const gridOptions = reactive<any>({
    align: 'center',
    border: true,
    columns: [
        { field: 'productName', title: '产品名称' },
        { field: 'category', title: '产品类目' },
        { field: 'brand', title: '品牌' },
        { field: 'model', title: '型号' },
        { field: 'attribute', title: '规格属性' },
        { field: 'unit', title: '单位' },
        { field: 'agreementPrice', title: '单价(元)' },
        { field: 'quantity', title: '数量' },
        { slots: { default: 'total' }, title: '总价' },
        { field: 'deliverAccumulativeTotal', title: '累计发货数量' },
        { field: 'acceptAccumulativeTotal', title: '累计验收数量' },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 350,
    keepSource: true,
    loading: false,
    showOverflow: true,
})

function goBack() {
    router.back()
}

const showSave = computed(() => data.value?.orderStatus === 3 && data.value?.supplierOperable === 1)

const isEdit = computed(() => data.value?.orderStatus === 3)

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    const valid = await formEl.validate()
    if (valid) {
        const params = {
            id: String(id.value),
            ...form.value,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                router.replace('/supplier-pages/order-management/sales-order')
            },
        })
    }
}
watchEffect(() => {
    if (data.value) {
        console.log(data.value)
        gridOptions.data = cloneDeep(data.value?.orderProductsVOS ?? [])
    }
})
</script>

<template>
    <el-skeleton v-if="isLoading"
                 :rows="5"
    />

    <div v-else>
        <ElCard mb-20>
            <div class="info-title">
                订单信息
            </div>

            <el-form :model="form"
                     label-width="auto"
            >
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="项目名称:">
                            {{ data?.projectName }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="订单名称:">
                            {{ data?.orderName }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="采购下单人:">
                            {{ data?.purchaser }}
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="下单人手机号:">
                            {{ data?.purchaserPhone }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="战略协议:">
                            {{ data?.agreementName }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="采购商名称:">
                            {{ data.partyA }}
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="收货地址:">
                            {{ data?.deliveryAddress }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="期望交货日期:">
                            {{ data?.expectedDeliveryStartDate }} - {{ data?.expectedDeliveryEndDate }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="备注:">
                            {{ data?.remark }}
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ElCard>

        <ElCard mb-20>
            <div class="info-title">
                产品信息
            </div>

            <el-form :model="form"
                     label-width="auto"
            >
                <el-row :gutter="20">
                    <el-col :span="3">
                        <el-form-item label="运输费:">
                            {{ data?.transportationCost }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-form-item label="安装费:">
                            {{ data?.installCost }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-form-item label="其他费用:">
                            {{ data?.otherCost }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="3"
                            :offset="12"
                    >
                        <el-form-item label="订单总额:">
                            <span style="color: red">{{ data?.totalPrice }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="附件信息:">
                            {{ data?.user }}
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <SearchTable v-bind="gridOptions"
                         ref="tableRef"
                         :loading="gridOptions.loading"
            >
                <template #total="{ row }">
                    {{ NP.round(row.agreementPrice * row.quantity, 2) }}
                </template>
            </SearchTable>
        </ElCard>

        <ElCard mb-20>
            <div class="info-title">
                收货信息
            </div>

            <el-form ref="formRef"
                     :inline="true"
                     :model="form"
                     :rules="isEdit ? rules : {}"
                     class="demo-form-inline"
            >
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="预计发货时间"
                                      prop="estimatedShippingDate"
                        >
                            <el-date-picker v-if="isEdit"
                                            v-model="form.estimatedShippingDate"
                                            type="date"
                                            placeholder="选择日期"
                                            clearable
                                            value-format="YYYY-MM-DD"
                            />

                            <span v-else>{{ data?.estimatedShippingDate }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="供应商联络人"
                                      prop="supplierContactName"
                        >
                            <el-input v-if="isEdit"
                                      v-model="form.supplierContactName"
                                      clearable
                            />

                            <span v-else>{{ data?.supplierContactName }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="联络人手机号"
                                      prop="supplierContactPhone"
                        >
                            <el-input v-if="isEdit"
                                      v-model="form.supplierContactPhone"
                                      clearable
                            />

                            <span v-else>{{ data?.supplierContactPhone }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="备注"
                              label-width="96"
                >
                    <el-input v-if="isEdit"
                              v-model="form.remark"
                              clearable
                    />

                    <span v-else>{{ data?.remark }}</span>
                </el-form-item>
            </el-form>
        </ElCard>

        <ElCard>
            <div style="text-align: center;">
                <ElButton @click="goBack">
                    取消
                </ElButton>

                <ElButton v-if="showSave"
                          type="primary"
                          :loading="isPending"
                          @click="doSave(formRef)"
                >
                    立即接单
                </ElButton>
            </div>
        </ElCard>
    </div>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 60px;
    border-bottom: 1px solid #e8eaec;
    margin-bottom: 20px;
}

.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>
